<template>
  <page-search
    :search-config="searchConfig"
    @queryClick="handleQueryClick"
    @resetClick="handleResetClick"
  />
  <page-content
    ref="contentRef"
    :content-config="contentConfig"
    @edit-click="handleEditClick"
    @new-click="handleNewClick"
  />
  <page-modal
    :modal-config="modalConfig"
    :other-info="otherInfo"
    ref="modalRef"
  >
    <template #menuList>
      <el-tree
        ref="treeRef"
        :data="entireMenusTree"
        show-checkbox
        accordion
        node-key="value"
        highlight-current
        :props="{
          children: 'children',
          label: 'label'
        }"
        @check="handleElTreeCheck"
      ></el-tree>
    </template>
  </page-modal>
</template>

<script setup lang="ts">
import { ElTree } from 'element-plus'
import { ref, nextTick } from 'vue'
import { storeToRefs } from 'pinia'

import PageSearch from '@/components/page/search/index.vue'
import PageContent from '@/components/page/content/index.vue'
import PageModal from '@/components/page/modal/index.vue'

import { searchConfig, modalConfig, contentConfig } from './config/index'
import { usePageModal, usePageContent } from '@/components/hooks/index'

import { useComponentRef } from '@/components/hooks'
import useMainStore from '@/store/main/main'

defineOptions({
  // 组件名称
  name: 'Role',
  // 继承透传，是否继承没在子组件声明的父组件的属性
  inheritAttrs: true
})

const { contentRef, handleQueryClick, handleResetClick } = usePageContent()
const { modalRef, handleEditClick, handleNewClick } = usePageModal(
  createCallback,
  editCallback
)

const mainStore = useMainStore()
const { entireMenusTree } = storeToRefs(mainStore)

const otherInfo = ref({})
// const checkedKeys = ref<string[]>([])
const handleElTreeCheck = (data1: any, data2: any) => {
  if (!data2.checkedNodes.length) return
  const { checkedKeys, halfCheckedKeys } = data2
  const menuIds = [...checkedKeys, ...halfCheckedKeys]
  otherInfo.value = { menuIds }
}

const treeRef = useComponentRef(ElTree)
function createCallback() {
  nextTick(() => {
    treeRef.value?.setCheckedKeys([])
  })
}

function editCallback(itemData: any) {
  nextTick(() => {
    const data = { ...itemData }
    // const ids = mapMenuListToIds(itemData.menuIds)
    const menuIds: string[] = [...data.menuIds]
    treeRef.value?.setCheckedKeys(menuIds, true)
  })
}
</script>

<style scoped lang="scss"></style>
